package com.sitech.portal.api;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.net.URLEncoder;
import java.util.Enumeration;

/**
 * Created by liujhc on 1/29.
 */
public class PortalApiFilter implements Filter {
    private String javascript = null, queryParam = "%26t=";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        javascript = filterConfig.getInitParameter("javascript");
        String query_param = filterConfig.getInitParameter("query_param");
        if (query_param != null) try {
            queryParam = URLEncoder.encode(query_param, "utf8") + "=";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private String toJson(String str) {
        return "\"" + str.replaceAll("\"", "\\\"").replaceAll("\n", "\\\n") + "\"";
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (req.getServletPath().endsWith("/?headers")) {
            // 获取header
            Enumeration headerNames = req.getHeaderNames();
            StringBuilder stringBuilder = new StringBuilder();
            while (headerNames.hasMoreElements()) {
                String headerName = (String) headerNames.nextElement();
                String header = req.getHeader(headerName);
                stringBuilder.append(",").append(toJson(headerName)).append(":").append(toJson(header));
            }
            resp.getWriter().append(request.getParameter("callback")).append("({").append(stringBuilder.substring(1)).append("});");
        } else if (req.getQueryString() != null && req.getQueryString().contains(queryParam) && req.getHeader("Accept").contains("text/html")) {
            // 是否需要注入js
            final ByteArrayOutputStream out = new ByteArrayOutputStream();
            HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(resp) {
                private PrintWriter writer;

                @Override
                public PrintWriter getWriter() throws IOException {
                    if (writer == null) {
                        writer = new PrintWriter(new OutputStreamWriter(out, getCharacterEncoding()));
                    }
                    return writer;
                }
            };
            filterChain.doFilter(req, responseWrapper);
            responseWrapper.getWriter().flush();
            if (out.size() > 0 && response.getContentType().contains("text/html")) {
                out.write(("<script src='" + javascript + "'></script>").getBytes());
            }
            resp.getWriter().write(out.toString(resp.getCharacterEncoding()));
        } else {
            filterChain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
